package com.cykj.user.service.impl;

import com.cykj.common.core.constant.SecurityConstants;
import com.cykj.common.core.utils.JwtUtils;
import com.cykj.common.core.utils.StringUtils;
import com.cykj.common.core.utils.uuid.UUID;
import com.cykj.common.redis.service.RedisService;
import com.cykj.user.domain.ScanLoginInfo;
import com.cykj.user.service.IScanLoginService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ScanLoginServiceImpl implements IScanLoginService {

    @Autowired
    private RedisService redisService;

    // 二维码有效期(秒)
    private static final long QR_CODE_EXPIRE = 60 * 5;
    // 登录令牌有效期(秒)
    private static final long LOGIN_TOKEN_EXPIRE = 60 * 30;

    @Override
    public Map<String, Object> generateQrCode() {
        String scanId = UUID.randomUUID().toString();
        String qrCodeContent = "login:" + scanId;
        
        // 存储扫码状态到Redis
        ScanLoginInfo scanInfo = new ScanLoginInfo();
        scanInfo.setScanId(scanId);
        scanInfo.setStatus("waiting");
        redisService.setCacheObject(getScanKey(scanId), scanInfo, QR_CODE_EXPIRE, TimeUnit.SECONDS);
        
        Map<String, Object> result = new HashMap<>();
        result.put("scanId", scanId);
        result.put("qrCodeContent", qrCodeContent);
        return result;
    }

    @Override
    public ScanLoginInfo checkScanStatus(String scanId) {
        return redisService.getCacheObject(getScanKey(scanId));
    }

  @Override
  public boolean confirmScan(String scanId, String token) {
      //验证Token有效性）
      String tokenKey = "login_tokens:" + token;
      if (!redisService.hasKey(tokenKey)) {
          return false; // Token无效或已过期
      }

      // 解析JWT获取用户信息
      Claims claims = JwtUtils.parseToken(token);
      Long userId = Long.parseLong(claims.get(SecurityConstants.DETAILS_USER_ID).toString());
      String username = claims.get(SecurityConstants.DETAILS_USERNAME).toString();

      // 查询扫码状态并更新
      ScanLoginInfo scanInfo = redisService.getCacheObject(getScanKey(scanId));
      if (scanInfo != null && "waiting".equals(scanInfo.getStatus())) {
          // 构建用户信息（可从用户服务查询完整信息）
          Map<String, Object> userInfo = new HashMap<>();
          userInfo.put("userId", userId);
          userInfo.put("username", username);

          // 更新扫码状态
          scanInfo.setStatus("confirmed");
          scanInfo.setToken(token); // 存储JWT令牌
          scanInfo.setUserInfo(userInfo);
          redisService.setCacheObject(getScanKey(scanId), scanInfo, LOGIN_TOKEN_EXPIRE, TimeUnit.SECONDS);
          return true;
      }
      return false;
  }

  @Override
  public ScanLoginInfo getScanStatus(String scanId) {
    ScanLoginInfo scanInfo = redisService.getCacheObject(getScanKey(scanId));
    if (scanInfo != null && scanInfo.getStatus().equals("expired")) {
      redisService.deleteObject(getScanKey(scanId));
      return null;
    }
    return scanInfo;
  }

    private String getScanKey(String scanId) {
        return "scan:login:" + scanId;
    }
}